export class Scanner {

    // 传入要遍历的字符串
    private source: string

    // 当前遍历的字符位置索引
    private index: number

    constructor(source: string) {
        this.source = source
        this.index = 0
    }

    /**
     * 返回当前位置的字符
     * @returns 
     */
    peek() {
        if (this.isAtEnd()) return ""
        return this.source.charAt(this.index)
    }

    /**
     * 当前索引向前一位, 返回当前索引指向的字符
     * @returns 
     */
    advance() {
        this.index++
        return this.source[this.index - 1]
    }

    /**
     * 匹配传入的字符串
     * @param expected 
     * @returns 
     */
    match(expected: string) {
        const subStr = this.source.substring(this.index + 1, this.index + expected.length + 1)
        if (subStr === expected) {
            this.index += expected.length + 1
            return true
        } else {
            return false
        }
    }

    /**
     * 获取当前索引下一位的字符
     * @returns 
     */
    peekNext() {
        if (this.isAtEnd()) return ""
        if (this.index + 1 >= this.source.length) {
            return ""
        }
        return this.source[this.index + 1]
    }

    /**
     * 确定是否完成遍历
     * @returns 
     */
    isAtEnd() {
        return this.index >= this.source.length
    }

}